<template>
  <ErrorUnknown v-if="error"></ErrorUnknown>
  <ScrollTabView
    v-else
    v-model="media"
    :tab-options="TAB_CREATOR"
    :hide-tabs="loading"
    :back-to-top-signal="backToTopSignal"
    @load="nextPage"
  >
    <template #outer-tabs>
      <div class="personal bg-background" :class="{ 'loading-skeleton': loading }">
        <div class="bg pointer">
          <EncryptImage
            :src="creator.background_img_mini"
            :full-src="creator.background_img"
            :object-fit="'cover'"
            click-to-full
          ></EncryptImage>
          <Avatar
            class="avatar pointer"
            :src="creator.avatar_mini"
            :full-src="creator.avatar"
            :radius="40"
            :vip="creator.is_vip"
            :vip-tier="creator.tier"
            click-to-full
          ></Avatar>
        </div>
        <div class="content">
          <div class="head">
            <Icon
              :name="`vip${creator.tier}`"
              size="0"
              v-if="creator.tier <= 4 && creator.tier >= 1"
              style="opacity: 0"
            ></Icon>
            <div v-if="!isSelf && creator.is_creator" class="feature gap-row-10">
              <Icon size="32" class="pointer" @click="toChat" name="chatBg"></Icon>
              <Icon
                size="32"
                name="moneyBg"
                class="pointer"
                @click="
                  donate(
                    { author: { aff: creator.aff, avatar: creator.avatar_mini, nickname: creator.nickname } },
                    13 /*gtmKey*/,
                  )
                "
              ></Icon>
              <FollowButton :user-id="creator.aff" :is-follow="creator.is_follow"></FollowButton>
            </div>
          </div>
          <div class="info gap-col-8">
            <div class="name row gap-row-5 align-center">
              <Icon :name="`vip${creator.tier}`" size="24" v-if="creator.tier <= 4 && creator.tier >= 1"></Icon>
              <div class="nickname font-size-16 font-weight-500 line-height-140">{{ creator.nickname }}</div>
              <div class="account font-size-16 font-weight-500 line-height-140 text-subtitle">
                {{ creator.username ? `@${creator.username}` : '' }}
              </div>
              <PremiumStar v-if="creator.is_vip"></PremiumStar>
              <Icon
                :name="`vip${creator.tier}`"
                size="24"
                v-if="creator.tier <= 4 && creator.tier >= 1"
                style="opacity: 0"
              ></Icon>
            </div>
            <div class="row gap-row-8">
              <div class="fans-count row gap-row-5">
                <div class="font-size-14 font-weight-500 line-height-140">{{ toKMBTString(creator.fans) }}</div>
                <div class="font-size-14 font-weight-500 line-height-140 text-subtitle">
                  {{ loading ? '' : $t('info.fans') }}
                </div>
              </div>
              <div class="publish-count row gap-row-5">
                <div class="font-size-14 font-weight-500 line-height-140">{{ toKMBTString(creator.post) }}</div>
                <div class="font-size-14 font-weight-500 line-height-140 text-subtitle">
                  {{ loading ? '' : $t('info.posts') }}
                </div>
              </div>
              <div class="watch-count row gap-row-5">
                <div class="font-size-14 font-weight-500 line-height-140">{{ toKMBTString(creator.view) }}</div>
                <div class="font-size-14 font-weight-500 line-height-140 text-subtitle">
                  {{ loading ? '' : $t('info.watches') }}
                </div>
              </div>
            </div>
            <div v-if="creator.link_instagram" class="link row gap-row-3">
              <div class="font-size-14 font-weight-500 line-height-140 text-subtitle">
                {{ loading ? '' : 'instagram: ' }}
              </div>
              <div class="font-size-14 font-weight-500 line-height-140 text-primary overflow-ellipsis">
                <a :href="addLinkQuery(creator.link_instagram)" target="_blank">
                  {{ parseAllLink(creator.link_instagram) }}
                </a>
              </div>
            </div>
            <div v-if="creator.link_twitter" class="link row gap-row-3">
              <div class="font-size-14 font-weight-500 line-height-140 text-subtitle">
                {{ loading ? '' : 'twitter: ' }}
              </div>
              <div class="font-size-14 font-weight-500 line-height-140 text-primary overflow-ellipsis">
                <a :href="addLinkQuery(creator.link_twitter)" target="_blank">
                  {{ parseAllLink(creator.link_twitter) }}
                </a>
              </div>
            </div>
            <div v-if="creator.link_tiktok" class="link row gap-row-3">
              <div class="font-size-14 font-weight-500 line-height-140 text-subtitle">
                {{ loading ? '' : 'tiktok: ' }}
              </div>
              <div class="font-size-14 font-weight-500 line-height-140 text-primary overflow-ellipsis">
                <a :href="addLinkQuery(creator.link_tiktok)" target="_blank">
                  {{ parseAllLink(creator.link_tiktok) }}
                </a>
              </div>
            </div>
            <div v-if="creator.link_vida" class="link row gap-row-3">
              <div class="font-size-14 font-weight-500 line-height-140 text-subtitle">
                {{ loading ? '' : 'vida: ' }}
              </div>
              <div class="font-size-14 font-weight-500 line-height-140 text-primary overflow-ellipsis">
                <a :href="addLinkQuery(creator.link_vida)" target="_blank">
                  {{ parseAllLink(creator.link_vida) }}
                </a>
              </div>
            </div>
            <div
              class="intro font-size-14 font-weight-400 line-height-140"
              :class="{ fold: introFold }"
              @click="introFold = !introFold"
            >
              {{ creator.bio }}
            </div>

            <button
              v-if="showSubscrbeBtn"
              class="sub-btn font-size-14 font-weight-500 line-height-140 primary-gradient"
              @click="
                subscribe({
                  item: {
                    author: {
                      aff: creator.aff,
                      avatar: creator.avatar_mini,
                      nickname: creator.nickname,
                      username: creator.username,
                      price: creator.subscribe_price,
                    },
                  },
                  gtmKey: 18,
                })
              "
            >
              {{ $t('label.personalSubscribeBtn', { price: toFixedString(creator.subscribe_price, 2) }) }}
            </button>
            <Banner v-if="creator.ad" :item="creator.ad" :event-id="69"></Banner>
          </div>
        </div>
      </div>
    </template>
    <template #tab-content-1>
      <MediaRow
        class="px-4"
        :items="freeDataList"
        :loading="freeLoading"
        :no-more="freeNoMore"
        @click:item="onItemClick"
      ></MediaRow>
    </template>
    <template #tab-content-2>
      <MediaRow
        class="px-4"
        :items="subsDataList"
        :loading="subsLoading"
        :no-more="subsNoMore"
        @click:item="onItemClick"
      ></MediaRow>
    </template>
    <template #tab-content-3>
      <MediaRow
        class="px-4"
        :items="shopDataList"
        :loading="shopLoading"
        :no-more="shopNoMore"
        @click:item="onItemClick"
      ></MediaRow>
    </template>
  </ScrollTabView>
</template>

<script setup>
import { computed, inject, provide, ref, shallowRef, watch } from 'vue'
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useAccountStore } from '@/store/account'
import { useCreatorStore } from '@/store/creator'
import { addLinkQuery, parseAllLink, toFixedString, toKMBTString } from '@/utils/string-helper'
import Banner from '@/components/banner/Banner.vue'
import ErrorUnknown from '@/components/common/ErrorUnknown.vue'
import PremiumStar from '@/components/common/PremiumStar.vue'
import ScrollTabView from '@/components/layout/ScrollTabView.vue'
import MediaRow from '@/components/media/MediaRow.vue'
import Avatar from '@/components/multimedia/Avatar.vue'
import EncryptImage from '@/components/multimedia/EncryptImage.vue'
import { useDialog } from '@/compositions/viewer/dialog'
import { MEDIA_TYPE } from '@/constant'
import { TAB_CREATOR } from '@/constant/config'
import { trackEvent } from '@/gtm'
import FollowButton from './stateful/FollowButton.vue'

const viewerRouter = inject('viewerRouter')
const { nextToIndexedViewer, getMediaType, getFreeFetcher, getSubsFetcher, getShopFetcher } = viewerRouter

const props = defineProps({
  id: { type: Number },
  viewerIndex: { type: Number },
  active: { type: Boolean },
})

const backToTopSignal = ref(Date.now())
const loading = ref(true)
const error = ref(false)
const creator = shallowRef({})
const { getCreator } = useCreatorStore()

provide('adEventId', 67)

provide('creator', creator)
watch(
  () => props.id,
  async (id, prevId, onCleanup) => {
    if (!id) {
      loading.value = true
      creator.value = {}
      return
    }

    let cleanup = false
    onCleanup(() => (cleanup = true))

    // 載入開始
    loading.value = true
    error.value = false

    // 清空舊的讓 loading-skeleton 顯示出來
    creator.value = {}

    // scroll 回頂部
    backToTopSignal.value = Date.now()

    try {
      // 取得新的
      const newCreator = await getCreator(id)

      // 等待取得 creator 期間 props.id 已經被換掉了
      if (cleanup) return

      creator.value = newCreator
      updateMedia()
    } catch (e) {
      error.value = true
      console.warn(e)
    }

    // 載入結束
    loading.value = false
  },
  { immediate: true },
)

const mediaRef = shallowRef(null)
const media = computed({
  get: () => {
    return mediaRef.value ? mediaRef.value.value : MEDIA_TYPE.FREE
  },
  set(value) {
    if (mediaRef.value) {
      mediaRef.value.value = value
    }
  },
})

const freeFetcherRef = shallowRef(null)
const freeDataList = computed(() => (freeFetcherRef.value ? freeFetcherRef.value.dataList : []))
const freeLoading = computed(() => (freeFetcherRef.value ? freeFetcherRef.value.loading : false))
const freeNoMore = computed(() => (freeFetcherRef.value ? freeFetcherRef.value.noMore : false))

const subsFetcherRef = shallowRef(null)
const subsDataList = computed(() => (subsFetcherRef.value ? subsFetcherRef.value.dataList : []))
const subsLoading = computed(() => (subsFetcherRef.value ? subsFetcherRef.value.loading : false))
const subsNoMore = computed(() => (subsFetcherRef.value ? subsFetcherRef.value.noMore : false))

const shopFetcherRef = shallowRef(null)
const shopDataList = computed(() => (shopFetcherRef.value ? shopFetcherRef.value.dataList : []))
const shopLoading = computed(() => (shopFetcherRef.value ? shopFetcherRef.value.loading : false))
const shopNoMore = computed(() => (shopFetcherRef.value ? shopFetcherRef.value.noMore : false))

function updateMedia() {
  mediaRef.value = getMediaType(props.viewerIndex)
  freeFetcherRef.value = getFreeFetcher(props.viewerIndex)
  subsFetcherRef.value = getSubsFetcher(props.viewerIndex)
  shopFetcherRef.value = getShopFetcher(props.viewerIndex)
}

function nextPage() {
  switch (media.value) {
    case MEDIA_TYPE.FREE:
      freeFetcherRef.value?.nextPage()
      break
    case MEDIA_TYPE.SUBS:
      subsFetcherRef.value?.nextPage()
      break
    case MEDIA_TYPE.SHOP:
      shopFetcherRef.value?.nextPage()
      break
  }
}

// 判別是不是自己
const accountStore = useAccountStore()
const { userId } = storeToRefs(accountStore)
const isSelf = computed(() => creator.value.aff === userId.value)

// 給小費 & 訂閱 & 購買
const { afterLoginAction } = accountStore
const { donate, subscribe, shopBuy } = useDialog()

function onItemClick(index) {
  const item = (() => {
    switch (media.value) {
      case MEDIA_TYPE.FREE:
        return freeFetcherRef.value?.dataList[index]
      case MEDIA_TYPE.SUBS:
        return subsFetcherRef.value?.dataList[index]
      case MEDIA_TYPE.SHOP:
        return shopFetcherRef.value?.dataList[index]
    }
  })()

  // 訂閱
  if (item.need_subscribe) {
    subscribe({
      item: {
        author: {
          aff: item.author.aff,
          avatar: item.author.avatar,
          nickname: item.author.nickname,
          username: item.author.username,
          price: creator.value.subscribe_price,
        },
        id: item.id,
      },
      gtmKey: 27,
    })
  }

  // 購買單筆帖子
  else if (item.need_buy) {
    shopBuy(item)
  }

  // 前往下一頁播放器
  else {
    nextToIndexedViewer(index)
  }
}

const router = useRouter()
const toChat = afterLoginAction(() => {
  router.replace({ name: 'message', query: { id: props.id } })
  trackEvent({ key: 12, meta: { aff: props.id } })
})

// 自介是否折疊
const introFold = ref(true)

const showSubscrbeBtn = computed(() => {
  return (
    creator.value.subscribe_button && // 創作者有開啟訂閱按鈕
    creator.value.subscribe_price > 0 && // 訂閱金額要大於 0
    !creator.value.is_subscribe && // 用戶未訂閱
    !isSelf.value // 用戶跟創作者不是同一人
  )
})
</script>

<style lang="scss" scoped>
@import '@/assets/styles/loading-skeleton.scss';

.personal {
  .bg {
    height: 40.8vw;
    overflow: visible;
    position: relative;

    .avatar {
      position: absolute;
      bottom: -2.5rem;
      left: 1rem;
    }
  }

  .content {
    .head {
      height: 2.5rem;
      padding: 0 1rem;
      display: flex;
      justify-content: flex-end;
      align-items: flex-end;

      .feature {
        display: flex;
        justify-content: center;
        align-items: center;

        button {
          height: 2rem;
          display: flex;
          justify-content: center;
          align-items: center;

          ::v-deep(.icon) {
            margin-right: 0.3125rem;
          }
        }
      }
    }

    .info {
      padding: 1rem 1rem 0.5rem;

      .row {
        display: flex;
        flex-direction: row;
      }

      .link {
        .overflow-ellipsis {
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }

      .intro.fold {
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 3;
        -webkit-box-orient: vertical;
      }
    }

    .sub-btn {
      width: 100%;
      height: 2rem;
      margin-top: 0.5rem;
      border-radius: 1.25rem;
    }
  }

  &.loading-skeleton {
    .info .name,
    .info .fans-count,
    .info .publish-count,
    .info .watch-count,
    .info .link,
    .info .intro {
      @include loading-skeleton;
    }
    .info .name {
      width: 12rem;
      height: 1.375rem;
      border-radius: 0.25rem;
    }
    .info .fans-count,
    .info .publish-count,
    .info .watch-count {
      width: 5rem;
      height: 1.25rem;
      border-radius: 0.25rem;
    }
    .info .link {
      width: 13rem;
      height: 1.25rem;
      border-radius: 0.25rem;
    }
    .info .intro {
      height: 3.75rem;
      border-radius: 0.25rem;
    }
    .content .head .feature {
      display: none;
    }
  }
}

.desktop {
  .personal {
    .bg {
      height: calc(var(--desktop-main-width) * 0.408);
    }
  }
}
</style>
